package com.httpClient.chapter2;

import com.httpClient.util.ResponseUtil;
import com.sky.JULLog.MyJulLogger;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * @author : wushikai
 *         <p>
 *         date : 2024-06-20
 */
public class KeepAliveOfClient {


    private static Logger log = MyJulLogger.getLogger(KeepAliveOfClient.class);


    public static void main(String[] args) throws Exception {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");   //这样会输出代理class文件
        doRequest();
    }


    private static void doRequest( ) throws IOException {


        RequestConfig requestConfig = RequestConfig
                .custom()
                /*
                 * 从连接池中获取连接的超时时间，假设：连接池中已经使用的连接数等于setMaxTotal，新来的线程在等待1*1000
                 * 后超时，错误内容：org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
                 */
                .setConnectionRequestTimeout(1*1000)
                /*
                 * 这定义了通过网络与服务器建立连接的超时时间。
                 * Httpclient包中通过一个异步线程去创建与服务器的socket连接，这就是该socket连接的超时时间，
                 * 此处设置为2秒。假设：访问一个IP，192.168.10.100，这个IP不存在或者响应太慢，那么将会返回
                 * java.net.SocketTimeoutException: connect timed out
                 */
                .setConnectTimeout(5*1000)
                /*
                 * 指的是连接上一个url，获取response的返回等待时间，假设：url程序中存在阻塞、或者response
                 * 返回的文件内容太大，在指定的时间内没有读完，则出现
                 * java.net.SocketTimeoutException: Read timed out
                 */
                .setSocketTimeout(30*1000)
                .build();
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setConnectionTimeToLive(10, TimeUnit.SECONDS);
        httpClientBuilder.setDefaultRequestConfig( requestConfig);
        CloseableHttpClient httpclient  = httpClientBuilder.build();
        HttpGet req = new HttpGet("http://localhost:8080/xy/expose/merDetail");
        HttpResponse response = httpclient.execute(req);  //使用 httpClient 调用 get请求
        ResponseUtil.handleResponse(response);
        httpclient.getConnectionManager().shutdown();

    }


}
